package com.ruoyi.art.service.impl;



import com.ruoyi.art.domain.FileInfo;
import com.ruoyi.art.mapper.FileInfoMapper;
import com.ruoyi.art.service.FileService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    private final MinioClient minioClient;
    private final String defaultBucket;
    private final FileInfoMapper fileInfoMapper;

    @Value("${minio.endpoint}")
    private String beforeStr;


    public FileServiceImpl(MinioClient minioClient,
                           @Value("${minio.bucket-name}") String defaultBucket, FileInfoMapper fileInfoMapper) {
        this.minioClient = minioClient;
        this.defaultBucket = defaultBucket;
        this.fileInfoMapper = fileInfoMapper;
    }

    @Override
    public FileInfo uploadFile(MultipartFile file, int userId, int stuId) {
        try {
            String ext = file.getOriginalFilename()
                    .substring(file.getOriginalFilename().lastIndexOf('.'));
            String objectName = UUID.randomUUID().toString() + ext;
            // 上传到 MinIO
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(defaultBucket)
                            .object(objectName)
                            .stream(file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build()
            );
            // 构造访问 URL（假设已开启 HTTP 直链）
            String url = beforeStr + "/" + defaultBucket + "/" + objectName;
            // 保存元数据
            FileInfo info = new FileInfo();
            info.setFileName(file.getOriginalFilename());
            info.setContentType(file.getContentType());
            info.setBucketName(defaultBucket);
            info.setObjectName(objectName);
            info.setUrl(url);
            info.setSize(file.getSize());
            info.setUserId(userId);
            info.setStuId(stuId);
            info.setFileStatus(0);
//            this.save(info);

            return info;
        } catch (Exception e) {
            throw new RuntimeException("文件上传失败", e);
        }
    }

//    @Override
//    public FileInfo getFileInfo(Long id) {
//        return this.getById(id);
//    }

}
